<template>
    <a-modal :visible="localVisible" :title="title" :width="650" @ok="handleOk" @cancel="handleCancel">
        <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <div class="fieldset">
                <div class="legend">网关型号</div>
                <a-form-item label="网关选择" class="fieldset-item">
                    <a-select 
                        v-model="formData.gatewayType" 
                        style="width: 200px;" 
                        :disabled="!isGatewayTypeEditable"
                        @change="onGatewayTypeChange"
                    >
                        <a-select-option v-for="type in availableGatewayTypes" :key="type" :value="type">
                            {{ getGatewayDisplayName(type) }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </div>

            <div class="fieldset">
                <div class="legend">硬件信息</div>
                <div class="hardware-info-grid">
                    <span class="info-label">更新模式</span>
                    <span class="info-value">{{ formData.updateMode }}</span>
                    <span class="info-label">Io数量</span>
                    <span class="info-value">{{ formData.ioCount }}</span>
                    <span class="info-label">串口数量</span>
                    <span class="info-value">{{ formData.serialPortCount }}</span>
                    <span class="info-label">设备数量</span>
                    <span class="info-value">{{ formData.deviceCount }}</span>
                    <span class="info-label">变量数量</span>
                    <span class="info-value">{{ formData.variableCount }}</span>
                    <span class="info-label">控制主题</span>
                    <span class="info-value">{{ formData.controlTopicCount }}</span>
                    <span class="info-label">上传主题</span>
                    <span class="info-value">{{ formData.uploadTopicCount }}</span>
                    <span class="info-label">MQTT数量</span>
                    <span class="info-value">{{ formData.mqttCount }}</span>
                    <span class="info-label">硬件描述</span>
                    <span class="info-value">{{ formData.hardwareDescription }}</span>
                </div>
            </div>

            <a-form-item label="设备名称">
                <a-input v-model="formData.name" />
            </a-form-item>
            <a-form-item label="重名属性">
                <a-checkbox v-model="formData.allowDeviceRename">允许设备重名</a-checkbox>
                <a-checkbox v-model="formData.allowVariableRename">允许变量重名</a-checkbox>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script>
import { 
    getGatewayHardwareInfo, 
    getAvailableGatewayTypes, 
    getGatewayDisplayName,
    createDeviceRequestData 
} from '@/config/gateway-config'

export default {
    name: 'DeviceModal',
    props: {
        visible: {
            type: Boolean,
            required: true
        },
        title: {
            type: String,
            required: true
        },
        initialData: {
            type: Object,
            default: () => ({
                id: -1,
                groupId: -1,
                gatewayType: 'WG01',
                name: '',
                allowDeviceRename: false,
                allowVariableRename: false
            })
        }
    },
    data() {
        return {
            formData: this.initializeFormData()
        }
    },
    computed: {
        localVisible: {
            get() {
                return this.visible
            },
            set(value) {
                this.$emit('update:visible', value)
            }
        },
        availableGatewayTypes() {
            return getAvailableGatewayTypes()
        },
        isGatewayTypeEditable() {
            // 当 baseData.id 为 -1 时允许更改网关类型（新建设备）
            // 当 baseData.id 不为 -1 时不允许更改网关类型（编辑现有设备）
            return this.formData.id === -1
        }
    },
    watch: {
        visible(val) {
            if (val) {
                this.formData = this.initializeFormData()
            }
        },
        initialData: {
            handler() {
                this.formData = this.initializeFormData()
            },
            deep: true
        }
    },
    methods: {
        /**
         * 初始化表单数据
         */
        initializeFormData() {
            const baseData = { ...this.initialData }
            const hardwareInfo = getGatewayHardwareInfo(baseData.gatewayType || 'WG01')
            
            return {
                id: baseData.id || -1,
                groupId: baseData.groupId || -1,
                gatewayType: baseData.gatewayType || 'WG01',
                name: baseData.name || '',
                allowDeviceRename: baseData.allowDeviceRename || false,
                allowVariableRename: baseData.allowVariableRename || false,
                // 硬件信息从网关配置中获取
                ...hardwareInfo
            }
        },

        /**
         * 网关类型改变时的处理
         */
        onGatewayTypeChange(gatewayType) {
            console.log('🔄 [DeviceModal] 网关类型改变:', gatewayType)
            const hardwareInfo = getGatewayHardwareInfo(gatewayType)
            
            // 更新硬件信息
            Object.assign(this.formData, hardwareInfo)
            
            console.log('📋 [DeviceModal] 更新后的硬件信息:', hardwareInfo)
        },

        /**
         * 获取网关显示名称
         */
        getGatewayDisplayName(gatewayType) {
            return getGatewayDisplayName(gatewayType)
        },

        /**
         * 确认操作
         */
        handleOk() {
            if (!this.formData.name) {
                this.$message.error('项目名称不能为空')
                return
            }

            // 创建只包含7个核心字段的请求数据
            const requestData = createDeviceRequestData(this.formData)
            
            console.log('✅ [DeviceModal] 提交设备数据:', requestData)
            
            this.$emit('ok', requestData)
        },

        /**
         * 取消操作
         */
        handleCancel() {
            this.$emit('update:visible', false)
            this.$emit('cancel')
        }
    }
}
</script>

<style scoped>
.fieldset {
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    padding: 24px 16px 16px;
    margin-bottom: 24px;
    position: relative;
}
.fieldset .legend {
    position: absolute;
    top: -12px;
    left: 10px;
    background: #fff;
    padding: 0 8px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
}
.fieldset-item.ant-form-item {
    margin-bottom: 0;
}
.hardware-info-grid {
    display: grid;
    grid-template-columns: max-content 1fr;
    gap: 8px 16px;
}
.info-label {
    font-weight: bold;
    color: #333;
    text-align: right;
}
.info-value {
    color: #0052cc;
    font-family: 'Courier New', Courier, monospace;
}
</style>